package com.example.guiguiapplicatio.fragment.examination;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.guiguiapplicatio.api.GetExaminationDetailApi;
import com.example.guiguiapplicatio.api.InsertExaminationTableApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.GetExaminationDetailCallback;
import com.example.guiguiapplicatio.api.Interface.InsertExaminationTableCallback;
import com.example.guiguiapplicatio.api.ModifyExaminationApi;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.ExaminationDetail;
import com.example.guiguiapplicatio.Response.ExaminationTable;
import com.example.guiguiapplicatio.databinding.FragmentExaminationTableBinding;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;

public class ExaminationTableFragment extends Fragment implements GetExaminationDetailCallback, AllCallback, InsertExaminationTableCallback {
    FragmentExaminationTableBinding binding;
    private static final String EXAMINATION_ID = "examinationid";
    private static final String NAME = "name";
    private Integer examinationId;
    private String name;
    private int isModify = 0;
    private GetExaminationDetailApi getExaminationDetailApi;
    private InsertExaminationTableApi insertExaminationTableApi;
    private ModifyExaminationApi modifyExaminationApi;
    private EditText editText;
    private List<EditText> editTextList = new ArrayList<>();
    private ScrollView scrollView;
    private File file = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            examinationId = getArguments().getInt(EXAMINATION_ID);
            name = getArguments().getString(NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentExaminationTableBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        getExaminationDetailApi = new GetExaminationDetailApi();
        getExaminationDetailApi.setGetExaminationDetailCallback(this);
        getExaminationDetailApi.performExaminationDetail(examinationId);

        modifyExaminationApi = new ModifyExaminationApi();
        modifyExaminationApi.setAllCallback(this);

        insertExaminationTableApi=new InsertExaminationTableApi();
        insertExaminationTableApi.setInsertExaminationTableCallback(this);
//        截图
        scrollView = view.findViewById(R.id.scroll_id);

        setEditTextList();

        binding.modifyBtu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isModify == 1) {
                    isModify = 0;
                    binding.modifyBtu.setText("修改");
                    for (EditText editText : editTextList) {
                        editText.setEnabled(false);
                    }
                } else {
                    isModify = 1;
                    binding.modifyBtu.setText("保存");
                    for (EditText editText : editTextList) {
                        editText.setEnabled(true);
                    }
                }
            }
        });
        binding.comitBtu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showConfirmationDialog();
            }
        });
//        上传截图
        binding.qvTable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showConfirmationPicture(view);
            }
        });
//        binding.serviceBack.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_examinationTableFragment_to_examinationRecordFragment));
        binding.serviceBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.popBackStack();
            }
        });
        return view;
    }
    private void captureScrollViewContent(View rootView){
        // 获取当前 fragment 的根视图
        if (rootView == null) {
            Log.e("Error", "Root view is null");
            return;
        }

        // 获取 ConstraintLayout 的宽度和高度
        ConstraintLayout titleTop = rootView.findViewById(R.id.title_top);
        int width = titleTop.getWidth();
        int height = titleTop.getHeight();

        // 创建一个与 ConstraintLayout 相同大小的 Bitmap 对象
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        // 将 ConstraintLayout 的内容绘制到 Bitmap 上
        titleTop.draw(canvas);
//        View view = getActivity().getWindow().getDecorView();
//        //设置 View 允许绘制缓存
//        view.setDrawingCacheEnabled(true);
//        //得到绘制缓存 Bitmap
//        Bitmap bitmap = view.getDrawingCache();
        // 保存 Bitmap 到相册
        saveBitmapToGallery(bitmap);
    }

    private void saveBitmapToGallery(Bitmap bitmap) {
        try {
            String description = "ScrollView_Capture";
            ContentResolver contentResolver = requireContext().getContentResolver();
            // 保存图片到相册，并获取保存后的URI
            String savedUrl = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "ScrollView_Capture", description);
            if (savedUrl != null) {
                // 提示保存成功
                Log.d("info","保存成功"+savedUrl);
                // 将URI转换为文件路径
                String filePath = getRealPathFromURI(Uri.parse(savedUrl));
                Log.d("info","文件路径"+filePath);
                // 扫描文件，使其出现在相册中
                MediaScannerConnection.scanFile(getContext(), new String[]{filePath}, null, null);
                //转成file对象；
                file = new File(filePath);
                if (file.exists()) {
                    System.out.println("成功转换为 File 对象");
                } else {
                    System.out.println("文件不存在，转换失败");
                }
                //上传到后端
                ExaminationTable examinationTable=new ExaminationTable();
                examinationTable.setExaminationid(examinationId);
                if (file != null) {
                    insertExaminationTableApi.performExaminationTable(file,examinationTable);
                } else {
                    Toast.makeText(getContext(), "图片不存在！", Toast.LENGTH_SHORT).show();
                }
            } else {
                // 提示保存失败
                Log.d("info","保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("info","保存失败");
        }

    }

    // 将URI转换为文件路径
    private String getRealPathFromURI(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    private void findAllEditText(View view, List<EditText> editTextList) {
        if (view instanceof EditText) {
            editTextList.add((EditText) view);
            if (view instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) view;
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    findAllEditText(viewGroup.getChildAt(i), editTextList);
                }
            }
        }
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        super.onResume();
    }

    @Override
    public void onEDSuccess(ResponseBody<ExaminationDetail> responseBody) {
        Object data = responseBody.getData();
        ExaminationDetail examinationDetail = (ExaminationDetail) data;
        Log.d("info", "响应的体检数据数据：" + examinationDetail.toString());
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

                binding.edtName.setText(name);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String formatDate = dateFormat.format(examinationDetail.getStarttime());
                Log.d("info", "时间体检：" + formatDate);
                binding.examinationTime.setText(formatDate);
                Log.d("info", "体检：" + examinationDetail.getSymptom());
                binding.edtZhengzhuang.setText(examinationDetail.getSymptom());
                binding.edtTemperature.setText(examinationDetail.getTemperature());
                binding.edtMailv.setText(examinationDetail.getPulseRate());
                binding.edtHeight.setText(examinationDetail.getHeight());
                binding.edtWeight.setText(examinationDetail.getWeight());
                binding.edtYaowei.setText(examinationDetail.getWaist());
                binding.edtBmi.setText(examinationDetail.getMbi());
                binding.edtHuxi.setText(examinationDetail.getRespiratoryRate());
                binding.edtXueyaLeft.setText(examinationDetail.getLeftPressure());
                binding.edtXueyaRight.setText(examinationDetail.getRightPressure());
                binding.edtOldHealth.setText(examinationDetail.getOldHealthy());
                binding.edtOldZili.setText(examinationDetail.getOldSelfCare());
                binding.edtOldRenzhi.setText(examinationDetail.getOldCognition());
                binding.edtOldQinggan.setText(examinationDetail.getOldEmotion());
                binding.yinshiQingkuang.setText(examinationDetail.getDiet());
                binding.duanlianQingkuang.setText(examinationDetail.getExercise());
                binding.shuimianQingkuang.setText(examinationDetail.getSleep());
                binding.yinjiuQingkuang.setText(examinationDetail.getDrink());
                binding.workQingkuang.setText(examinationDetail.getWork());
                binding.zuichunQingkuang.setText(examinationDetail.getLip());
                binding.zhiciQingkuang.setText(examinationDetail.getDentalCaries());
                binding.yanhouQingkuang.setText(examinationDetail.getPharynx());
                binding.zuoyanEdit.setText(examinationDetail.getLeftEye());
                binding.youyanEdit.setText(examinationDetail.getRightEye());
                binding.tingliEdit.setText(examinationDetail.getHearing());
                binding.yundongEdit.setText(examinationDetail.getMotion());
                binding.yandiEdit.setText(examinationDetail.getFundus());
                binding.pifuEdit.setText(examinationDetail.getSkin());
                binding.niaodanbaiEdit.setText(examinationDetail.getUrineProtein());
                binding.niaotangEdit.setText(examinationDetail.getUrinarySugar());
                binding.niaotongtiEdit.setText(examinationDetail.getUrinaryKetoneBody());
                binding.niaoqianxueEdit.setText(examinationDetail.getUrinaryOccultBlood());
                binding.niaoQitaEdit.setText(examinationDetail.getUrinaryOther());
                binding.kongfuxuetangEdit.setText(examinationDetail.getKongfuxuetang());
                Glide.with(getContext())
                        .load(examinationDetail.getElectrocardiogram()) // 设置图片的URL
                        .into(binding.xinImg); // 设置要显示图片的ImageView

                binding.zhenduanResultEdit.setText(examinationDetail.getDiagnosticResults());
                binding.niaoWeiliangEdit.setText(examinationDetail.getMicroUrineProtein());
                binding.dabianQianxueEdit.setText(examinationDetail.getFecalOccultBlood());
                binding.tangXuedanbaiEdit.setText(examinationDetail.getGlycosylatedHemoglobin());
                binding.yiganKangyuanEdit.setText(examinationDetail.getHbsag());
                binding.bingzhuanAnEdit.setText(examinationDetail.getSerumAlanineAminotransferase());
                binding.caozhuanAnEdit.setText(examinationDetail.getSerumAspartateAminotransferase());
                binding.baidanbaiEdit.setText(examinationDetail.getAlbumin());
                binding.zongdanhongsuEdit.setText(examinationDetail.getTotalBilirubin());

            }
        });
    }

    @Override
    public void onEDFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "体检表详情响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void setEditTextList() {
        editTextList.add(binding.edtZhengzhuang);
        editTextList.add(binding.edtTemperature);
        editTextList.add(binding.edtMailv);
        editTextList.add(binding.edtHeight);
        editTextList.add(binding.edtWeight);
        editTextList.add(binding.edtYaowei);
        editTextList.add(binding.edtBmi);
        editTextList.add(binding.edtHuxi);
        editTextList.add(binding.edtXueyaLeft);
        editTextList.add(binding.edtXueyaRight);
        editTextList.add(binding.edtOldHealth);
        editTextList.add(binding.edtOldZili);
        editTextList.add(binding.edtOldRenzhi);
        editTextList.add(binding.edtOldQinggan);
        editTextList.add(binding.yinshiQingkuang);
        editTextList.add(binding.duanlianQingkuang);
        editTextList.add(binding.shuimianQingkuang);
        editTextList.add(binding.yinjiuQingkuang);
        editTextList.add(binding.workQingkuang);
        editTextList.add(binding.zuichunQingkuang);
        editTextList.add(binding.zhiciQingkuang);
        editTextList.add(binding.yanhouQingkuang);
        editTextList.add(binding.zuoyanEdit);
        editTextList.add(binding.youyanEdit);
        editTextList.add(binding.tingliEdit);
        editTextList.add(binding.yundongEdit);
        editTextList.add(binding.yandiEdit);
        editTextList.add(binding.pifuEdit);
        editTextList.add(binding.niaodanbaiEdit);
        editTextList.add(binding.niaotangEdit);
        editTextList.add(binding.niaotongtiEdit);
        editTextList.add(binding.niaoqianxueEdit);
        editTextList.add(binding.niaoQitaEdit);
        editTextList.add(binding.kongfuxuetangEdit);
        editTextList.add(binding.zhenduanResultEdit);
        editTextList.add(binding.niaoWeiliangEdit);
        editTextList.add(binding.dabianQianxueEdit);
        editTextList.add(binding.tangXuedanbaiEdit);
        editTextList.add(binding.yiganKangyuanEdit);
        editTextList.add(binding.bingzhuanAnEdit);
        editTextList.add(binding.caozhuanAnEdit);
        editTextList.add(binding.baidanbaiEdit);
        editTextList.add(binding.zongdanhongsuEdit);
    }

    private void setExaminationDetail(ExaminationDetail examinationDetail) {
        // 从 EditText 中获取数据并设置到 ExaminationDetail 对象中
        examinationDetail.setExaminationId(examinationId);
        examinationDetail.setSymptom(binding.edtZhengzhuang.getText().toString());
        examinationDetail.setTemperature(binding.edtTemperature.getText().toString());
        examinationDetail.setPulseRate(binding.edtMailv.getText().toString());
        examinationDetail.setHeight(binding.edtHeight.getText().toString());
        examinationDetail.setWeight(binding.edtWeight.getText().toString());
        examinationDetail.setWaist(binding.edtYaowei.getText().toString());
        examinationDetail.setMbi(binding.edtBmi.getText().toString());
        examinationDetail.setRespiratoryRate(binding.edtHuxi.getText().toString());
        examinationDetail.setLeftPressure(binding.edtXueyaLeft.getText().toString());
        examinationDetail.setRightPressure(binding.edtXueyaRight.getText().toString());
        examinationDetail.setOldHealthy(binding.edtOldHealth.getText().toString());
        examinationDetail.setOldSelfCare(binding.edtOldZili.getText().toString());
        examinationDetail.setOldCognition(binding.edtOldRenzhi.getText().toString());
        examinationDetail.setOldEmotion(binding.edtOldQinggan.getText().toString());
        examinationDetail.setDiet(binding.yinshiQingkuang.getText().toString());
        examinationDetail.setExercise(binding.duanlianQingkuang.getText().toString());
        examinationDetail.setSleep(binding.shuimianQingkuang.getText().toString());
        examinationDetail.setDrink(binding.yinjiuQingkuang.getText().toString());
        examinationDetail.setWork(binding.workQingkuang.getText().toString());
        examinationDetail.setLip(binding.zuichunQingkuang.getText().toString());
        examinationDetail.setDentalCaries(binding.zhiciQingkuang.getText().toString());
        examinationDetail.setPharynx(binding.yanhouQingkuang.getText().toString());
        examinationDetail.setLeftEye(binding.zuoyanEdit.getText().toString());
        examinationDetail.setRightEye(binding.youyanEdit.getText().toString());
        examinationDetail.setHearing(binding.tingliEdit.getText().toString());
        examinationDetail.setMotion(binding.yundongEdit.getText().toString());
        examinationDetail.setFundus(binding.yandiEdit.getText().toString());
        examinationDetail.setSkin(binding.pifuEdit.getText().toString());
        examinationDetail.setUrineProtein(binding.niaodanbaiEdit.getText().toString());
        examinationDetail.setUrinarySugar(binding.niaotangEdit.getText().toString());
        examinationDetail.setUrinaryKetoneBody(binding.niaotongtiEdit.getText().toString());
        examinationDetail.setUrinaryOccultBlood(binding.niaoqianxueEdit.getText().toString());
        examinationDetail.setUrinaryOther(binding.niaoQitaEdit.getText().toString());
        examinationDetail.setKongfuxuetang(binding.kongfuxuetangEdit.getText().toString());
        examinationDetail.setDiagnosticResults(binding.zhenduanResultEdit.getText().toString());
        examinationDetail.setMicroUrineProtein(binding.niaoWeiliangEdit.getText().toString());
        examinationDetail.setFecalOccultBlood(binding.dabianQianxueEdit.getText().toString());
        examinationDetail.setGlycosylatedHemoglobin(binding.tangXuedanbaiEdit.getText().toString());
        examinationDetail.setHbsag(binding.yiganKangyuanEdit.getText().toString());
        examinationDetail.setSerumAlanineAminotransferase(binding.bingzhuanAnEdit.getText().toString());
        examinationDetail.setSerumAspartateAminotransferase(binding.caozhuanAnEdit.getText().toString());
        examinationDetail.setAlbumin(binding.baidanbaiEdit.getText().toString());
        examinationDetail.setTotalBilirubin(binding.zongdanhongsuEdit.getText().toString());

    }

    //    修改确认框
    private void showConfirmationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("确认");
        builder.setMessage("确认提交修改吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ExaminationDetail examinationDetail = new ExaminationDetail();
                setExaminationDetail(examinationDetail);
                Log.d("info", examinationDetail.toString());
                modifyExaminationApi.performModifyExaminationApi(examinationDetail);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    //    截图确认框
    private void showConfirmationPicture(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("确认");
        builder.setMessage("确认提交体检表吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                captureScrollViewContent(view);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onSuccess(ResponseBody<Object> responseBody) throws ParseException {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "修改体检表响应成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "修改体检表响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onTSuccess(ResponseBody<Object> responseBody) throws ParseException {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "获取体检表成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onTFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "获取体检表响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}